<template>
  <div class="contract-editor-container">
    <!-- 工具栏 -->
    <el-text v-if="!show"> 请选择先选择材料</el-text>
    <h1 v-else> {{material.title}}</h1>
    <el-card class="mb-4">
        <el-button type="primary" @click="saveContract">保存合同</el-button>
        <el-button @click="previewContract">预览</el-button>
    </el-card>

      <!-- 合同编辑区域 -->
      <el-card>
        <div class="contract-content">
          <div class="text-center mb-8">
            <h1 class="text-2xl font-bold">授	权	委	托 书</h1>
            <p class="text-left">致：苏州华靖建筑科技有限公司</p>
          </div>
          <div class="mb-6">
            <p>　　本授权委托书声明：
              <span class="edit" :contenteditable="isEdit('name')" @input="onChange('name', $event.target)">{{ contract.name }}</span>
              （以下称我司）委托
              <span class="edit" :contenteditable="isEdit('user')" @input="onChange('user', $event.target)">{{ contract.user }}</span>
              作为我司合法代理人，全权代表我司办理
              <span class="edit" :contenteditable="isEdit('project')" @input="onChange('project', $event.target)">{{ contract.project }}</span>
              工程材料采购项目【对应编号为
              <span class="edit" :contenteditable="isEdit('number')" @input="onChange('number', $event.target)">{{ contract.number }}</span>
              的《材料采购合同》】相关工作，包括但不限于确认结算金额及扣款金额、来往函件签收、确认等所有事务。</p>
            <p>　　对代理人在办理上述事项过程中所签署的有关文件和相关代理行为，我司均予以认可，我司将承担全部法律后果和法律责任。</p>
            <p>　　委托权限自签署之日起至上述事项办完为止。</p>
            <p>　　代理人无转委托权，特此授权。</p>
            <p>　　代理人：
              <span class="edit" :contenteditable="isEdit('user')" @input="onChange('user', $event.target)">{{ contract.user }}</span>
              性 别：
              <span class="edit" :contenteditable="isEdit('sex')" @input="onChange('sex', $event.target)">{{ contract.sex }}</span>
              身份证号码：
              <span class="edit" :contenteditable="isEdit('idcard')" @input="onChange('idcard', $event.target)">{{ contract.idcard }}</span>
            </p>
            <p>　　联系电话：
              <span class="edit" :contenteditable="isEdit('mobile')" @input="onChange('mobile', $event.target)">{{ contract.mobile }}</span>
              ，联系地址:
              <span class="edit" :contenteditable="isEdit('address')" @input="onChange('address', $event.target)">{{ contract.address }}</span>
            </p>
          </div>
          <el-row>
            <el-col :span="18"></el-col>
            <el-col :span="6">
              <p>单位（盖章）：<span class="edit" :contenteditable="isEdit('name')" @input="onChange('name', $event.target)">{{ contract.name }}</span></p>
              <p>委   托  人：</p>
              <p>法人签字或盖章）</p>
              <p>日       期：<span class="edit" :contenteditable="isEdit('date')" @input="onChange('date', $event.target)">{{ contract.date }}</span></p>
            </el-col>
          </el-row>
        </div>
    </el-card>

    <!-- 预览弹窗 -->
    <el-dialog v-model="previewVisible" title="合同预览" width="80%">
      <div class="contract-preview" >
        <!-- 预览内容与编辑区域相同，但所有内容都不可编辑 -->
        <div ref="pdfContent" v-html="previewHtml" class="contract-content" />
      </div>
      
      <template #footer>
        <el-button type="primary" @click="exportToPdf">导出为PDF</el-button>
        <el-button @click="previewVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElCard, ElButton, ElDialog } from 'element-plus';
import html2pdf from 'html2pdf.js';
import http from '../../../util/request';
const pdfContent = ref(null);

const show = ref(false)
const material = ref({id:0,title:'',is:false});
let is = sessionStorage.getItem('material_contract');
if(is){
  show.value = true
  material.value = JSON.parse(is)
}

// 初始化合同数据
const contract = ref<any>({
  name: '徐州柏杨树装饰工程有限公司',
  user: '汤 磊',
  project: '/',
  number:'20250809112',
  sex:'男',
  idcard:'320325 1981 0620 2634',
  mobile: '181121752707',
  address: '邳州官湖镇上海路木制品工园',
  date: '2021年4月25日',
});

// 可编辑区域设置
const dialogVisible = ref(false);
const editableSections = ref<string[]>([
  'name',
  'user',
  'project',
  'number:',
  'sex',
  'idcard',
  'mobile',
  'address',
  'date',
]);

// 状态管理
const isSaved = ref(false);
const previewVisible = ref(false);
const previewHtml = ref('');

// 判断区域是否可编辑
const isEdit = (section: string) => {
  return editableSections.value.includes(section);
};

const onChange = (section:any, value: any) => {
  contract.value[section] = value.innerText;
  isSaved.value = false;
};

const getData = () => {
    http.post('/material/template',{material_contract_id:material.value.id,type:'auth'}).then((response:any)=>{
      if(response.data.data){
        contract.value = response.data.data.content
        material.value.is = true
      }
      dialogVisible.value = true;
    })
}

// 保存合同
// 保存合同
const saveContract = () => {
  // 模拟保存操作
  let request:any = null
  let content:string = JSON.stringify(contract.value)
    if(material.value.is){
        request = http.patch('/material/template',{material_contract_id:material.value.id,type:'auth',content:content})
    }else{
        request = http.put('/material/template',{material_contract_id:material.value.id,type:'auth',content:content})
    }
    request.then((response:any)=>{
      if(response.data.code == 200){
        isSaved.value = true;
        ElMessage.success('合同已保存');
        material.value.is = true
      }
    })
};

// 预览合同
const previewContract = () => {
  // 生成预览HTML，将所有可编辑区域变为不可编辑
  const tempDiv = document.createElement('div');
  const contractContent = document.querySelector('.contract-content')?.cloneNode(true);
  
  if (contractContent) {
    tempDiv.appendChild(contractContent);
    const editableElements = tempDiv.querySelectorAll('.edit');
    editableElements.forEach(el => {
      (el as HTMLElement).contentEditable = 'false';
      el.removeAttribute('class');
    });
    previewHtml.value = tempDiv.innerHTML;
    previewVisible.value = true;
  }
};

// 页面加载时显示可编辑区域设置按钮
onMounted(() => {
  getData();
});

// 导出PDF的方法
const exportToPdf = () => {
  if (!pdfContent.value) return;

  // 配置选项
  const opt = {
    margin: 10,
    filename: '导出的文档.pdf',
    image: { type: 'jpeg', quality: 0.98 },
    html2canvas: { scale: 2, useCORS: true },
    jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
  };

  // 生成PDF
  html2pdf().from(pdfContent.value).set(opt).save();
};
</script>

<style scoped>
.contract-editor-container {
  padding: 20px;
}

.contract-content {
  line-height: 1.8;
  font-size: 16px;
}

.edit {
  border-bottom: 1px dashed #edd32c;
  padding: 0 4px;
  min-width: 60px;
  display: inline-block;
}

.edit[contenteditable="true"] {
  background-color: #edd32c;
  cursor: text;
}

.edit[contenteditable="true"]:focus {
  outline: 1px solid #edd32c;
  border-radius: 2px;
}

.contract-preview {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
}
</style>
